﻿/*
 * Created by SharpDevelop.
 * User: Intel
 * Date: 24.01.2014
 * Time: 15:17
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using Region.Utils;
namespace Region
{
  public partial class Report : DBObject
  {
      /*
  	class TableList<T>:Dictionary<String,Dictionary<String,Dictionary<String,List<T>>>>
  	{
		  public Boolean Add(String Table, String Row,String Col, T item)
	    {
        if (!this.ContainsKey(Table)) this[Table] = new Dictionary<String, Dictionary<String, List<T>>>();
        if (!this[Table].ContainsKey(Row)) this[Table][Row] = new Dictionary<String, List<T>>();
        if (!this[Table][Row].ContainsKey(Col)) this[Table][Row][Col] = new List<T>();
        this[Table][Row][Col].Add(item);
        return true;
      }
		  public Int32 getNum(String Table, String Row,String Col)
      {
        if (!this.ContainsKey(Table)) return 0;
        if (!this[Table].ContainsKey(Row)) return 0;
        if (!this[Table][Row].ContainsKey(Col)) return 0;
        return this[Table][Row][Col].Count;
      }
  	}
  	static bool clearReportResultAll(Engine engine, Report report)
    {
      String Table = "T1";
      foreach(String Row in new String[]{"R1","R2","R3","R4","R5","R6","R7","R8","R9","R10","R11","R12","R13","R14","R15","R16"})
        foreach(String Column in new String[]{"C2","C3","C4","C5","C6","C7"})
          report.SetValue(Table, Row, Column, "");
      return true;
    }
  	static bool ProcessReportResultAll_ReadPlan(Engine engine, Report report, TaskManager.Task task,  Dictionary<Int32,List<Plan>> PlanMonth)
  	{
  	  DateTime Start = report.Start; 
      DateTime End = report.End;
  	  var listPlan = new PlanList(engine);
      listPlan.setWhere("IgnorePage", true);
      listPlan.setWhere("ParentOtdelID", report.OtdelID);
      listPlan.setWhere("PlanYear", Start.Year);
      listPlan.Filter();
      Int32 CountPlan = listPlan.NumLines;
      if (task!=null){task.TaskName="Чтение базы данных плана"; task.TaskMax = CountPlan;}
      for(Int32 i=0;i<CountPlan;i++)
      {
        task.TaskValue = i;
        PlanListLine line = listPlan.getLine(i);
        Plan plan = engine.getPlan(line.PlanID);
        if (plan.RegNum>0)
        {
          Int32 M = plan.Start.Month;
          if (!PlanMonth.ContainsKey(M)) 
            PlanMonth[M] = new List<Plan>();
          PlanMonth[M].Add(plan);
        }
      }
      return true;      
  	}
  	static bool ProcessReportResultAll_ReadRaspor(Engine engine, Report report, TaskManager.Task task,  List<Raspor> Raspors)
  	{
  	  DateTime Start = report.Start; 
      DateTime End = report.End;  	  
  	  var list = new RasporList(engine);
      list.setWhere("IgnorePage", true);
      list.setWhere("ParentOtdelID", report.OtdelID);
      list.setWhere("StartStart", report.Start.Date.AddMonths(-1));// -1 - Дата начала проверкиза месяц до на чала периода
      list.setWhere("StartEnd", report.End.Date);// -1 - Дата начала проверкиза месяц до на чала периода
      list.setWhere("Podpis", true);
      list.Filter();
      if (task!=null){task.TaskName="Чтение базы данных распоряжений"; task.TaskMax = list.NumLines;}
        for(Int32 i=0;i<list.NumLines;i++)
      {
        task.TaskValue = i;
        RasporListLine line = list.getLine(i);
        Raspor raspor = engine.getRaspor(line.RasporID);
        if (raspor.RasporNum>0) 
        	Raspors.Add(raspor);
      }
      return true;         
  	}
  	/// <summary> Сопостовление с планом </summary>
  	static bool ProcessReportResultAll_PlanToRaspor(Engine engine, Report report, TaskManager.Task task, List<Raspor> Raspors, Dictionary<Int32,List<Plan>> PlanMonth, Dictionary<Int32,Raspor> PlanIDRaspor)
  	{
  	  DateTime Start = report.Start; 
      DateTime End = report.End;  	  
      Int32 Count = Raspors.Count;
      for(Int32 i=0;i<Count;i++)
      {      	
      	Raspor raspor = Raspors[i];
  
        if (raspor.CheckPlan && raspor.Start.DateTime>=Start &&  raspor.Start.DateTime<End)
        {
          Int32 M = raspor.Start.Month;
          foreach(var p in PlanMonth[M])
            if (p.KontID==raspor.KontID)
              PlanIDRaspor[p.PlanID] = raspor;
        }     	
      }
      return true;
  	}
  	static bool ProcessReportResultAll_MonthRaspor(Engine engine, Report report, TaskManager.Task task,TableList<Raspor> DataRaspor)
  	{
  	  DateTime Start = report.Start; 
      DateTime End = report.End;
      var S = new DateTime[]{new DateTime(Start.Year,1,1),new DateTime(Start.Year,2,1),new DateTime(Start.Year,3,1),new DateTime(Start.Year,4,1),new DateTime(Start.Year,5,1),new DateTime(Start.Year,6,1),new DateTime(Start.Year,7,1),new DateTime(Start.Year,8,1),new DateTime(Start.Year,9,1), new DateTime(Start.Year,10,1),new DateTime(Start.Year,11,1),new DateTime(Start.Year,12,1),new DateTime(Start.Year,1,1),new DateTime(Start.Year,1,1),new DateTime(Start.Year,1,1)};
      var E = new DateTime[]{new DateTime(Start.Year,2,1),new DateTime(Start.Year,3,1),new DateTime(Start.Year,4,1),new DateTime(Start.Year,5,1),new DateTime(Start.Year,6,1),new DateTime(Start.Year,7,1),new DateTime(Start.Year,8,1),new DateTime(Start.Year,9,1),new DateTime(Start.Year,10,1),new DateTime(Start.Year,11,1),new DateTime(Start.Year,12,1),new DateTime(Start.Year+1,1,1),new DateTime(Start.Year,4,1),new DateTime(Start.Year,7,1),new DateTime(Start.Year,10,1)};
      var Table1Column = new List<String>{"CEnd_1","CEnd_2","CEnd_3","CEnd_4","CEnd_5","CError_2","COsn_SanZpp","COsn_San","COsn_Zpp","COsn_Reg","CNar_1","CNar_2","CNar_3"};
      var Table2Column = new List<String>{"CNotEnd","CEnd_1","CEnd_2","CEnd_3","CEnd_4","CEnd_5","CError_1","CError_2","COsn_SanZpp","COsn_San","COsn_Zpp","COsn_Reg","CNar_1","CNar_2","CNar_3"};
      foreach(Int32 Osnov in new Int32[]{13,15,16,17,18})
        Table2Column.Add("COsnov"+Osnov.ToString());
      var Col = new Dictionary<String,List<String>>(){{"T1",Table1Column},{"T2",Table2Column}};
      foreach(var T in new String[]{"T1","T2"})
        foreach(var Column in Col[T])
        if (DataRaspor.getNum(T,"R16",Column)>0)
          foreach(var raspor in DataRaspor[T]["R16"][Column])
      {
        for(Int32 m=0;m<S.Length;m++)
        {
          if(raspor.AktDate.Date >= S[m] && raspor.AktDate.Date < E[m])
            DataRaspor.Add(T,"R"+(m+1),Column,raspor);
        }
      }
      
      foreach(var Column in new String[]{"CError_1","CNotEnd"})
        if (DataRaspor.getNum("T1","R16",Column)>0)
          foreach(var raspor in DataRaspor["T1"]["R16"][Column])
      {
        for(Int32 m=0;m<S.Length;m++)
        {
          if(raspor.Start.Date >= S[m] && raspor.Start.Date < E[m])
            DataRaspor.Add("T1","R"+(m+1),Column,raspor);
        }
        
      }      
      return true;      
  	}
   	static bool ProcessReportResultAll_ProcessPlan(Engine engine, Report report, TaskManager.Task task, Dictionary<Int32,List<Plan>> PlanMonth, TableList<Plan> DataPlan, Dictionary<Int32,Raspor> PlanIDRaspor)
  	{
   	  DateTime Now = DateTime.Now.Date;
      foreach(var pm in PlanMonth)
        foreach(var p in pm.Value)
      {
        Int32 m = pm.Key;
        DataPlan.Add("T1","R"+m,"CPlan_1",p);
        if (m>=1&&m<4) DataPlan.Add("T1","R13","CPlan_1",p);
        if (m>=1&&m<7) DataPlan.Add("T1","R14","CPlan_1",p);
        if (m>=1&&m<10) DataPlan.Add("T1","R15","CPlan_1",p);
        DataPlan.Add("T1","R16","CPlan_1",p);
        if (!PlanIDRaspor.ContainsKey(p.PlanID) && p.Start.DateTime<Now)
        {
          DataPlan.Add("T1","R"+m,"CPlan_2",p);
          if (m>=1&&m<4)DataPlan.Add("T1","R13","CPlan_2",p);
          if (m>=1&&m<7)DataPlan.Add("T1","R14","CPlan_2",p);
          if (m>=1&&m<10)DataPlan.Add("T1","R15","CPlan_2",p);
          DataPlan.Add("T1","R16","CPlan_2",p);
        }
      } 
      return true;      
  	}
    static bool ProcessReportResultAll_ProcessRaspor(Engine engine, Report report, TaskManager.Task task, TableList<Raspor> DataRaspor,List<Raspor> Raspors)
    {
  	  DateTime Start = report.Start; 
      DateTime End = report.End;
      DateTime Now = DateTime.Now.Date;
      Int32 Count = Raspors.Count;
      Regex RSan1 = new Regex(@".*[\s]?52.{1,5}ФЗ.*");
      Regex RSan2 = new Regex(@".*санитарно.{0,5}эпидемиолог.*");
      Regex RZpp1 = new Regex(@".*[\s]?2300-1.{1,5}.*");
      Regex RZpp2 = new Regex(@".*защит.{0,5}прав.{0,5}потреб.*");      
      Regex RTr1 = new Regex(@".*Техн.{1,10}регл.*");  

      if (task!=null){task.TaskName="Расспоряжения"; task.TaskMax = Count;}
      for(Int32 i=0;i<Count;i++)
      {
      	task.TaskValue = i;
      	Raspor raspor = Raspors[i];
        if (raspor.Del==0)
        {
          
          String Table = raspor.CheckPlan?"T1":"T2";
          
            // Строка 16
            if (!raspor.AktDate.Empty && raspor.AktDate.DateTime>=Start && raspor.AktDate.DateTime<End)
            {
              DataRaspor.Add(Table,"R16","CEnd_1",raspor);
              if (raspor.NNar==0) 
                DataRaspor.Add(Table,"R16","CEnd_2",raspor);
              if (raspor.Protokols.Count>0)
                DataRaspor.Add(Table,"R16","CEnd_3",raspor);
              if (raspor.ExpertsInfo.Length>100)
                DataRaspor.Add(Table,"R16","CEnd_4",raspor);
              Int32 NumNac=0;
              foreach(var p in raspor.Protokols)
                if (p.Value.MeasureID==1 || // Штраф
                    p.Value.MeasureID==2 || // Предупреждение
                    p.Value.MeasureID==3 || // Устное замечание
                    p.Value.MeasureSudID == 1 || // Предупреждение
                    p.Value.MeasureSudID == 2 || // Дисквалификация
                    p.Value.MeasureSudID == 3 || // Арест
                    p.Value.MeasureSudID == 4 || // Адм. штраф
                    p.Value.MeasureSudID == 5 || // Адм. штраф с конфискацией
                    p.Value.MeasureSudID == 6 || // Приостановление деятельности
                    p.Value.MeasureSudID == 7 || // Приостановление деятельности с конфискацией
                    p.Value.MeasureSudID == 8 || // прекращено
                    p.Value.MeasureSudID == 9 || // отменено
                    p.Value.MeasureSudID == 10 // устное замечание
                   )
                  NumNac += 1;
              if (NumNac>0)
                DataRaspor.Add(Table,"R16","CEnd_5",raspor);
              Boolean San=false,Zpp=false,Reg=false;
              if (RSan1.IsMatch(raspor.OsnovInfo) || RSan2.IsMatch(raspor.OsnovInfo))
                San=true;
              if (RZpp1.IsMatch(raspor.OsnovInfo) || RZpp2.IsMatch(raspor.OsnovInfo))
                Zpp=true;
              if (RTr1.IsMatch(raspor.OsnovInfo))
                Reg=true;
              if (San==true && Zpp==true) DataRaspor.Add(Table,"R16","COsn_SanZpp",raspor);
              else if (San==true) DataRaspor.Add(Table,"R16","COsn_San",raspor);
              else if (Zpp==true) DataRaspor.Add(Table,"R16","COsn_Zpp",raspor);
              
              if (Reg==true) DataRaspor.Add(Table,"R16","COsn_Reg",raspor);
              if (raspor.NNar==-1 || raspor.Predstav==-1 || raspor.NStop==-1 || raspor.SLic==-1|| raspor.NLic==-1 || raspor.Nar1==-1 || raspor.Nar2==-1 || raspor.Nar3==-1)
                DataRaspor.Add(Table,"R16","CError_2",raspor);
              if (raspor.Nar1==1)
                DataRaspor.Add(Table,"R16","CNar_1",raspor);
              if (raspor.Nar2==1)
                DataRaspor.Add(Table,"R16","CNar_2",raspor);
              if (raspor.Nar3==1)
                DataRaspor.Add(Table,"R16","CNar_3",raspor);
            }
            if (raspor.AktDate.Empty && raspor.Start.DateTime>=Start && raspor.Start.DateTime<End)
              if (raspor.End.DateTime<Now)
                DataRaspor.Add(Table,"R16","CError_1",raspor);
              else
                DataRaspor.Add(Table,"R16","CNotEnd",raspor);
          if (raspor.CheckPlan==false)
          {
            Boolean OOther = true;
            foreach(Int32 Osnov in new Int32[]{13,15,16,17,18})
              if (raspor.OsnovID==Osnov) 
            {
                OOther=false;
                DataRaspor.Add("T2","R16","COsnov"+Osnov.ToString(),raspor);
            }
            if (OOther) 
              DataRaspor.Add("T2","R16","COsnovOther",raspor);
          }
        }
      } 
      return true;      
    }
  	static bool ProcessReportResultAll_Save(Engine engine, Report report, TaskManager.Task task,TableList<Raspor> DataRaspor, TableList<Plan> DataPlan)
  	{
  	  
  	  foreach(var T in new String[]{"T1","T2"})
    	{
  	    var ListError2 = new StringBuilder();
    	  if (DataRaspor.getNum(T,"R16","CError_2")>0)
    	   foreach(Raspor raspor in DataRaspor[T]["R16"]["CError_2"])
    	  {
    	    ListError2.Append("Распоряжение №");
    	    ListError2.Append(raspor.RasporNum);
    	    ListError2.Append(" от ");
    	    ListError2.Append(raspor.Date.ToShortDateString());
    	    ListError2.Append("  [");
    	    ListError2.Append(raspor.IspUser.FIO);
    	    ListError2.Append("]  ");
    	    ListError2.Append(raspor.Kont.KontName);
    	    ListError2.Append("<br/>");
    	  }
    	  report.SetValue(T, "R0", "CError_2",ListError2.ToString());
  	  }
      var ListOsnovOther = new StringBuilder();
      Dictionary<Int32,String> OsnovList = engine.Osnov;
  	  if (DataRaspor.getNum("T2","R16","COsnovOther")>0)
    	   foreach(Raspor raspor in DataRaspor["T2"]["R16"]["COsnovOther"])
  	  {
  	    ListOsnovOther.Append("Распоряжение №");
  	    ListOsnovOther.Append(raspor.RasporNum);
  	    ListOsnovOther.Append(" от ");
  	    ListOsnovOther.Append(raspor.Date.ToShortDateString());
  	    ListOsnovOther.Append("  [");
  	    ListOsnovOther.Append(raspor.IspUser.FIO);
  	    ListOsnovOther.Append("]  ");
  	    ListOsnovOther.Append(raspor.Kont.KontName);
        ListOsnovOther.Append("  ");
        ListOsnovOther.Append(OsnovList[raspor.OsnovID]);
  	    ListOsnovOther.Append("<br/>");
  	  }
      report.SetValue("T1", "R0", "Date",DateTime.Now.ToShortDateString());
      report.SetValue("T2", "R0", "COsnovOther",ListOsnovOther.ToString());
      
  	  foreach(var Column in new String[]{"CPlan_1","CPlan_2"})
        for(Int32 m=1;m<=16;m++)
          report.SetValue("T1", "R"+m, Column, DataPlan.getNum("T1", "R"+m, Column).ToString());
  	  
      var Table1Row = new String[]{"R1","R2","R3","R4","R5","R6","R7","R8","R9","R10","R11","R12","R13","R14","R15","R16"};
      var Table1Column = new String[]{"CNotEnd","CEnd_1","CEnd_2","CEnd_3","CEnd_4","CEnd_5","CError_1","CError_2","COsn_SanZpp","COsn_San","COsn_Zpp","COsn_Reg","CNar_1","CNar_2","CNar_3"};

      String Table1 = "T1";
      foreach(String Row in Table1Row)
        foreach(String Column in Table1Column)
          report.SetValue(Table1, Row, Column, DataRaspor.getNum(Table1,Row,Column).ToString());
      
      var Table2Row = new String[]{"R1","R2","R3","R4","R5","R6","R7","R8","R9","R10","R11","R12","R13","R14","R15","R16"};
      var Table2Column = new List<String>{"CNotEnd","CEnd_1","CEnd_2","CEnd_3","CEnd_4","CEnd_5","CError_1","CError_2","COsn_SanZpp","COsn_San","COsn_Zpp","COsn_Reg","CNar_1","CNar_2","CNar_3"};
      foreach(Int32 Osnov in new Int32[]{13,15,16,17,18})
        Table2Column.Add("COsnov"+Osnov.ToString());
      String Table2 = "T2";
      foreach(String Row in Table2Row)
        foreach(String Column in Table2Column)
          report.SetValue(Table2, Row, Column, DataRaspor.getNum(Table2,Row,Column).ToString());
      report.save();  	
      return true;      
  	}

    static bool ProcessReportResultAll(Engine engine, Report report, TaskManager.Task task)
    {  
      
      if (task!=null) task.TaskTitle = "Отчёт ЭФФЕКТИВНОСТЬ НАДЗОРА \n"+engine.getOtdel(report.OtdelID).OtdelName + " с "+report.Start.ToShortDateString()+" по "+report.End.ToShortDateString();
      var DataRaspor = new TableList<Raspor>();
      var DataPlan = new TableList<Plan>();
      var PlanMonth = new Dictionary<Int32, List<Plan>>();
      var Raspors = new List<Raspor>();
      var PlanIDRaspor = new Dictionary<Int32, Raspor>();
      if (!clearReportResultAll(engine,report)) return false;
      if (!ProcessReportResultAll_ReadPlan(engine, report, task,  PlanMonth)) return false;
      if (!ProcessReportResultAll_ReadRaspor(engine, report, task,  Raspors)) return false;
      if (!ProcessReportResultAll_PlanToRaspor(engine, report, task, Raspors, PlanMonth,  PlanIDRaspor)) return false;
      if (!ProcessReportResultAll_ProcessPlan(engine, report, task, PlanMonth, DataPlan,PlanIDRaspor)) return false;
      if (!ProcessReportResultAll_ProcessRaspor(engine, report, task, DataRaspor, Raspors)) return false;
      if (!ProcessReportResultAll_MonthRaspor(engine, report, task, DataRaspor)) return false;
      if (!ProcessReportResultAll_Save(engine, report, task, DataRaspor, DataPlan)) return false;
      return true;
    }*/
  }
}
